package bigdata.monitor.binlog.utils;

import bigdata.monitor.binlog.entity.MonitorRule;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

/**
 * 构建综合校验 SQL（1 消息 → 1 次查询）
 */
@Slf4j
public class CombinedRuleSqlBuilder {

    /**
     * 构建 SQL: SELECT (expr1) AS rule_code1, (expr2) AS rule_code2 FROM ...
     */
    public static String buildSql(String binlogJson, List<MonitorRule> rules) {
        if (rules.isEmpty()) {
            throw new IllegalArgumentException("Rules list is empty");
        }

        // 转义单引号
        String escapedJson = binlogJson.replace("'", "''");

        // 构建 SELECT 子句
        StringBuilder selectClause = new StringBuilder();
        for (int i = 0; i < rules.size(); i++) {
            MonitorRule rule = rules.get(i);
            if (i > 0) selectClause.append(", ");

            // 验证 ruleCode 合法性（防止 SQL 注入）
            if (!rule.getRuleCode().matches("^[a-zA-Z0-9_]+$")) {
                throw new IllegalArgumentException("Invalid ruleCode: " + rule.getRuleCode());
            }

            String dorisExpr = RuleConditionConverter.toDorisExpression(rule);
            selectClause.append("(")
                    .append(dorisExpr)
                    .append(") AS ")
                    .append(rule.getRuleCode());
        }

        return String.format(
                "SELECT %s FROM (SELECT json_parse('%s') AS data) t1",
                selectClause.toString(),
                escapedJson
        );
    }
}